package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 关注或取消关注
     *
     * @param dto 前端传输的数据
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        //检查参数
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "用户未登录");
        }

        short operation = dto.getOperation();
        if (operation != 0 && operation != 1) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //如果是0要关注
        ZSetOperations<String, String> forZSet = redisTemplate.opsForZSet();
        if (operation == 0) {

            Double score = forZSet.score(UserRelationConstants.FOLLOW_LIST + apUser.getId()
                    , dto.getAuthorApUserId().toString());
            if(score!=null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"你已经关注过该作者了");
            }
            //是否自己关注自己
            if (apUser.getId().equals(dto.getAuthorApUserId())) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"请勿自己关注自己");
            }
            //关注实现  zadd follow  zadd fans
            forZSet.add(UserRelationConstants.FOLLOW_LIST+ apUser.getId()
                    ,dto.getAuthorApUserId().toString(),System.currentTimeMillis());

            forZSet.add(UserRelationConstants.FANS_LIST+dto.getAuthorApUserId()
                    ,apUser.getId().toString(),System.currentTimeMillis());
        }else{
            //如果是1 取关
            forZSet.remove(UserRelationConstants.FOLLOW_LIST+ apUser.getId()
                    ,dto.getAuthorApUserId().toString());
            //删除集合中的数据
            forZSet.remove(UserRelationConstants.FANS_LIST+dto.getAuthorApUserId()
                    ,apUser.getId().toString());
        }

        return ResponseResult.okResult();
    }
}